<!--
+----------------------------------------------------------------------
| 友得云客  - 开启房产营销新纪元
+----------------------------------------------------------------------
| Copyright (c) 2019~2023 优得（西安）信息科技有限公司版权所有
+----------------------------------------------------------------------
| Licensed 友得云客不是自由软件 未经允许不可移除相关版权
+----------------------------------------------------------------------
| Author: www.youdeyunke.com
+----------------------------------------------------------------------
-->
<template>
  <div v-cloak v-loading="loading">
    <media-manager :limit="1" :file-types="['image']" :show.sync="showMM" @selected="imageSelected"></media-manager>
    <div class="tools header" style="">
      <!-- <el-button type="primary" size="small">上传图片</el-button>
      <el-button type="primary" size="small" @click="createItemClick">添加楼栋</el-button> -->
    </div>
    <div
      :style="'margin: 0 auto;width: ' + bgWidth + 'px;height:' + bgHeight + 'px;outline: 2px solid #f0f0f0;display: flex;align-items: center;position: relative;'">
      <canvas ref="canvas" :width="bgWidth" :height="bgHeight" @dblclick="editHandleClick" @mousedown="handleMouseDown"
        @mousemove="handleMouseMove" @mouseup="handleMouseUp"></canvas>
      <div v-if="!bgImgUrl"
        :style="`position: absolute;top:${bgHeight / 2}px;text-align: center;width: 100%;color: #ccc;font-size: 20px;`">
        未设置总平图，请点击下方选择图片按钮，设置总平图后，设置楼栋。</div>
    </div>

    <div style="font-size: 12px; color: #999;text-align: center;margin-top: 20px;">
      <i class="el-icon-info"></i>
      双击已设置楼栋，可编辑楼栋信息
    </div>

    <div style="margin: 20px;display: flex;justify-content: center;">
      <el-button type="primary" size="small" @click="zoomIn" icon="el-icon-zoom-in"
        :disabled="bgScale >= 1.5">放大</el-button>
      <el-button type="primary" size="small" icon="el-icon-zoom-out" @click="zoomOut"
        :disabled="bgScale <= 0.5">缩小</el-button>
      <el-button type="primary" icon="el-icon-picture" size="small" @click="showMM = true">选择图片</el-button>
      <el-button type="primary" icon="el-icon-plus" size="small" @click="createItemClick">添加楼栋</el-button>
      <el-button type="primary" icon="el-icon-check" size="small" @click="saveHandle">保存</el-button>
    </div>

    <el-dialog :visible.sync="show" v-loading="loading" :close-on-click-modal="false" :close-on-press-escape="false"
      :show-close="false" width="400px" title="楼栋编辑">
      <!-- 使用elform进行表单布局，对currentItem进行编辑 -->
      <el-form>
        <el-form-item>
          <!-- <el-input v-model="currentItem.text"></el-input> -->
          <el-select style="width: 90%;" v-model="currentItem.text" placeholder="楼栋/单元">
            <el-option v-for="b, index in buildings" :key="index" :label="b" :value="b">
            </el-option>
          </el-select>
          <i style="margin-left: 8px" v-show="!loading" class="el-icon-refresh-right" @click="loadBuildList"></i>
        </el-form-item>
      </el-form>
      <div style="font-size: 12px; color: #999;text-align: center;margin-top: 20px;">
        <i class="el-icon-info"></i>
        请在销控管理中上传信息后，再选择楼栋
      </div>
      <div slot="footer">
        <el-button size="mini" @click="closeClick" icon="el-icon-close">取消</el-button>
        <el-button v-if="currentIndex !== -1" type="danger" size="mini" @click="deleteItemClick"
          icon="el-icon-delete">删除</el-button>
        <el-button type="primary" size="mini" @click="saveItemClick" icon="el-icon-check">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MediaManager from "@/components/MediaManager/Index";
import { getBuildingRoomList } from "@/api/post";
import {
  savePostAirview,
  getPostsAirview
} from "@/api/post";
export default {
  components: { MediaManager },
  data() {
    return {
      loading: false,
      show: false,
      showMM: false, // 文件选择框
      startX: 0, // 拖动开始位置X
      startY: 0, // 拖动开始位置Y,
      canvas: null,
      ctx: null,
      items: [
        // { width: 100, height: 40, x: 50, y: 50, text: "red" },
        // { width: 75, height: 40, x: 200, y: 150, text: "green" },
        // { width: 75, height: 40, x: 200, y: 150, text: "green" },
      ],
      bgImgUrl: '',
      // "https://tcdn.udeve.net/fang2021/bd100e61-f2aa-4334-aaab-6d0f998c020e.jpg",
      bgWidth: 1000,
      bgHeight: 750,
      currentItem: {
        width: null,
        height: 80,
        text: "",
      },
      currentIndex: -1,
      isDragging: false, // 是否正在拖拽
      bgScale: 1, // 初始放大缩小比例
      bgPositionX: 0, // 背景图位置 X
      bgPositionY: 0, // 背景图位置 Y

      buildings: [], // 楼栋列表
    };
  },
  props: {
    postId: { type: Number, default: null },
  },

  watch: {},
  mounted: function () {
    this.canvas = this.$refs.canvas;
    this.ctx = this.canvas.getContext("2d");
    this.loadData()
    this.loadBuildList()
  },

  computed: {
    primaryColor: function () {
      return "#fa6a00";
    },
  },

  methods: {
    zoomIn() {
      if (!this.bgImgUrl) {
        this.$message.warning('请先选择背景图片')
        return
      }
      this.bgScale += 0.1;

      this.clearCanvas();
      this.renderCanvas();
    },
    zoomOut() {
      if (!this.bgImgUrl) {
        this.$message.warning('请先选择背景图片')
        return
      }
      if (this.bgScale > 0.2) {
        this.bgScale -= 0.1;

        this.clearCanvas();
        this.renderCanvas();
      }
    },
    imageSelected: function (imgs) {
      this.bgImgUrl = imgs[0].url;
      this.showMM = false;
      this.loadBgImage();
    },
    clearCanvas() {
      this.ctx.clearRect(0, 0, this.bgWidth, this.bgHeight);
      this.ctx.drawImage(
        this.bgImage,
        this.bgPositionX,
        this.bgPositionY,
        this.bgWidth * this.bgScale,
        this.bgHeight * this.bgScale
      );
    },
    loadBgImage() {
      this.loading = true;
      this.ctx.clearRect(0, 0, this.bgWidth, this.bgHeight);
      var bgImage = new Image();
      var _this = this;
      bgImage.src = this.bgImgUrl;
      this.bgImage = bgImage;
      bgImage.onload = () => {
        _this.ctx.drawImage(
          bgImage,
          _this.bgPositionX,
          _this.bgPositionY,
          this.bgWidth * this.bgScale,
          this.bgHeight * this.bgScale
        );
        _this.renderCanvas();
      };
    },
    renderCanvas() {
      // 渲染json数组中的方框

      for (let obj of this.items) {
        this.drawBox(obj);
      }
      this.loading = false;
    },
    drawBox(box) {
      const cornerRadius = 10; // 圆角半径
      box.width = Number(box.width);
      box.height = Number(box.height);

      // 绘制填充矩形
      this.ctx.fillStyle = this.primaryColor;
      this.ctx.beginPath();
      this.ctx.moveTo(box.x + cornerRadius, box.y);
      this.ctx.lineTo(box.x + box.width - cornerRadius, box.y);
      this.ctx.arc(
        box.x + box.width - cornerRadius,
        box.y + cornerRadius,
        cornerRadius,
        -Math.PI / 2,
        0
      );
      this.ctx.lineTo(box.x + box.width, box.y + box.height - cornerRadius);
      this.ctx.arc(
        box.x + box.width - cornerRadius,
        box.y + box.height - cornerRadius,
        cornerRadius,
        0,
        Math.PI / 2
      );
      this.ctx.lineTo(box.x + cornerRadius, box.y + box.height);
      this.ctx.arc(
        box.x + cornerRadius,
        box.y + box.height - cornerRadius,
        cornerRadius,
        Math.PI / 2,
        Math.PI
      );
      this.ctx.lineTo(box.x, box.y + cornerRadius);
      this.ctx.arc(
        box.x + cornerRadius,
        box.y + cornerRadius,
        cornerRadius,
        Math.PI,
        -Math.PI / 2
      );
      this.ctx.closePath();
      this.ctx.fill();

      // 绘制描边矩形（白边）
      this.ctx.strokeStyle = "#fff";
      this.ctx.lineWidth = 2; // 设置描边宽度为2
      this.ctx.beginPath();
      this.ctx.moveTo(box.x + cornerRadius, box.y);
      this.ctx.lineTo(box.x + box.width - cornerRadius, box.y);
      this.ctx.arc(
        box.x + box.width - cornerRadius,
        box.y + cornerRadius,
        cornerRadius,
        -Math.PI / 2,
        0
      );
      this.ctx.lineTo(box.x + box.width, box.y + box.height - cornerRadius);
      this.ctx.arc(
        box.x + box.width - cornerRadius,
        box.y + box.height - cornerRadius,
        cornerRadius,
        0,
        Math.PI / 2
      );
      this.ctx.lineTo(box.x + cornerRadius, box.y + box.height);
      this.ctx.arc(
        box.x + cornerRadius,
        box.y + box.height - cornerRadius,
        cornerRadius,
        Math.PI / 2,
        Math.PI
      );
      this.ctx.lineTo(box.x, box.y + cornerRadius);
      this.ctx.arc(
        box.x + cornerRadius,
        box.y + cornerRadius,
        cornerRadius,
        Math.PI,
        -Math.PI / 2
      );
      this.ctx.closePath();
      this.ctx.stroke();

      // 绘制文字
      this.ctx.fillStyle = "#fff"; // 设置字体颜色为白色
      this.ctx.textAlign = "center"; // 水平居中对齐
      this.ctx.textBaseline = "middle"; // 垂直居中对齐
      this.ctx.font = "bold 20px Arial"; // 设置字体为粗体、20px大小的 Arial
      this.ctx.fillText(
        box.text,
        box.x + box.width / 2,
        box.y + box.height / 2
      );
    },

    createItemClick() {
      if (!this.bgImgUrl) {
        this.$message.warning('请先选择背景图片')
        return
      }
      this.show = true;
    },
    closeClick() {
      this.show = false;
      this.currentIndex = -1;
      this.currentItem = {
        width: null,
        height: 80,
        text: "",
      };
    },
    editHandleClick(event) {
      console.log(event);
      const rect = this.canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;

      // 判断点击位置是否已有方框
      const clickedBox = this.items.find((obj) => {
        return (
          x >= obj.x &&
          x <= obj.x + obj.width &&
          y >= obj.y &&
          y <= obj.y + obj.height
        );
      });

      if (clickedBox) {
        // 编辑方框属性
        // 在这里你可以弹出对话框或修改数据模型
        console.log("编辑方框", clickedBox);
        const index = this.items.indexOf(clickedBox);
        console.log("点击的对象在数组中的索引为：", index);
        this.currentItem = clickedBox;
        this.currentIndex = index;
        this.show = true;
      }
    },
    saveItemClick() {
      var _this = this;

      if (!this.currentItem.text) {
        this.$message.warning("文字不能为空");
        return;
      }
      // 新增方框检查一下楼栋是否存在

      if (this.items.some(item => item.text == this.currentItem.text)) {
        this.$message.warning(`楼栋 ${this.currentItem.text} 已存在，无需重复添加`)
        return
      }
      // width等于文字长度乘以24，height等于40
      this.currentItem.width = this.currentItem.text.length * 40;

      // 如果currentIndex = -1，说明是新增的方框，将方框添加到数组中
      if (this.currentIndex === -1) {
        this.currentItem.x = 0;
        this.currentItem.y = 0;
        this.items.push(this.currentItem);
        this.clearCanvas();
        this.renderCanvas();
        this.show = false;
        this.currentIndex = -1;
        this.currentItem = {
          width: null,
          height: 80,
          text: "",
        };
        return;
      }
      // 如果currentIndex不等于-1，说明是编辑已有的方框，将方框替换数组中的原有方框
      this.items[this.currentIndex] = this.currentItem;
      this.show = false;
      this.currentIndex = -1;
      this.currentItem = {
        width: null,
        height: 80,
        text: "",
      };
      this.clearCanvas();
      this.renderCanvas();
    },
    deleteItemClick() {
      if (this.currentIndex === -1) {
        return;
      }
      this.items.splice(this.currentIndex, 1);
      this.show = false;
      this.currentIndex = -1;
      this.currentItem = {
        width: null,
        height: 80,
        text: "",
      };
      this.clearCanvas();
      this.renderCanvas();
    },
    handleMouseDown(event) {
      const rect = this.canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;

      // 判断点击位置是否已有方框
      const clickedBox = this.items.find((obj) => {
        return (
          x >= obj.x &&
          x <= obj.x + obj.width &&
          y >= obj.y &&
          y <= obj.y + obj.height
        );
      });
      this.isDragging = true;
      if (clickedBox) {
        this.startX = x - clickedBox.x;
        this.startY = y - clickedBox.y;
        this.currentItem = clickedBox;
        const index = this.items.indexOf(clickedBox);
        this.currentIndex = index;
        return;
      }
      // if (
      //   x >= this.bgPositionX &&
      //   x <= this.bgPositionX + this.bgWidth * this.bgScale &&
      //   y >= this.bgPositionY &&
      //   y <= this.bgPositionY + this.bgHeight * this.bgScale
      // ) {
      // this.isDragging = true;
      this.startX = x - this.bgPositionX;
      this.startY = y - this.bgPositionY;
      // }
    },
    handleMouseMove(event) {
      var _this = this;
      if (this.isDragging) {
        const rect = this.canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;

        if (this.currentIndex !== -1) {
          this.items[this.currentIndex].x = x - this.startX;
          this.items[this.currentIndex].y = y - this.startY;
        } else {
          this.bgPositionX = x - this.startX;
          this.bgPositionY = y - this.startY;
        }
        this.clearCanvas();
        this.renderCanvas();
      }
    },
    handleMouseUp(event) {
      this.isDragging = false;
      this.currentIndex = -1;
      this.currentItem = { width: null, height: 80, text: "" };
      event.stopPropagation();
    },
    saveHandle() {
      this.loading = true
      var data = {
        bg_width: this.bgWidth,
        bg_height: this.bgHeight,
        bg_img_url: this.bgImgUrl,
        bg_img_scale: this.bgScale,
        bg_img_x: this.bgPositionX,
        bg_img_y: this.bgPositionY,
        items: this.items
      }
      if (data.bg_img_url === '') {
        this.$message.error('请上传背景图片')
        this.loading = false
        return
      }
      savePostAirview(this.postId, data).then(res => {
        this.loading = false
        if (res.code != 0) {
          return
        }
        this.$message.success('保存成功')
      }).catch((err) => {
        this.loading = false
        console.log(err);
      })
    },
    loadData() {
      this.loading = true
      getPostsAirview(this.postId).then(res => {
        this.loading = false
        if (res.code != 0) {
          return
        }
        if (res.data) {
          this.bgImgUrl = res.data.bg_img_url
          this.bgScale = res.data.bg_img_scale
          this.bgPositionX = res.data.bg_img_x
          this.bgPositionY = res.data.bg_img_y
          this.items = res.data.items
          this.loadBgImage()
        }
      }).catch((err) => {
        this.loading = false
        console.log(err);
      })
    },
    loadBuildList() {
      var q = { post_id: this.postId };
      this.loading = true
      var _this = this
      getBuildingRoomList(q).then((resp) => {
        this.loading = false;
        if (resp.status != 0) {
          return;
        }
        var rooms = resp.data;
        var buildings = rooms.map((room) => {
          return room.building;
        });
        // 去重
        buildings = Array.from(new Set(buildings)).sort();
        buildings = buildings.filter((building) => building);
        _this.buildings = buildings;

      }).catch((err) => {
        this.loading = false
        console.log(err);
      });


    },
  },
};
</script>
<style scoped>
.tools {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.header {
  margin-bottom: 10px;
}

.footer {
  margin-top: 10px;
}
</style>
